package com.ft.oa.service.check.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ft.oa.domain.Attachment;
import com.ft.oa.domain.approval.ApplyForApproval;
import com.ft.oa.domain.check.ExecProjectExamine;
import com.ft.oa.domain.check.ExecProjectProblem;
import com.ft.oa.domain.dto.knowledgeBase.AttachmentDto;
import com.ft.oa.domain.project.ExecProject;
import com.ft.oa.domain.project.ExecProjectContract;
import com.ft.oa.enums.DirectoryTypeEnum;
import com.ft.oa.enums.ManagerEnum;
import com.ft.oa.mapper.check.ExecProjectExamineMapper;
import com.ft.oa.mapper.check.ExecProjectProblemMapper;
import com.ft.oa.mapper.customer.ExecProjectContractMapper;
import com.ft.oa.mapper.project.ExecProjectMapper;
import com.ft.oa.service.approval.ApplyForApprovalService;
import com.ft.oa.service.check.ExecProjectExamineService;
import com.ft.oa.service.knowledgeBase.DirectoryService;
import com.ft.oa.service.project.ExecProjectService;
import com.ft.oa.service.project.ProjectWarrantyService;
import com.ft.oa.utils.SecurityUtils;
import com.ft.oa.web.check.rq.ExecProjectExaminePage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目验收管理
 */
@Service
public class ExecProjectExamineServiceImpl implements ExecProjectExamineService {

    @Resource
    private ExecProjectExamineMapper execProjectExamineMapper;

    @Resource
    private ExecProjectProblemMapper execProjectProblemMapper;

    @Resource
    private ExecProjectService execProjectService;

    @Resource
    private ExecProjectMapper execProjectMapper;

    @Resource
    private ExecProjectContractMapper execProjectContractMapper;

    @Resource
    private ApplyForApprovalService applyForApprovalService;
    
    @Resource
    private DirectoryService directoryService;
    
    @Resource
    private ProjectWarrantyService projectWarrantyService;

    /**
     * 添加项目验收信息
     *
     * @param execProjectExamine
     * @return
     */
    @Override
    @Transactional
    public int add(ExecProjectExamine execProjectExamine) {
        //处理附件
        List<AttachmentDto> attachments = execProjectExamine.getAttachments();
        if(attachments != null && attachments.size() > 0){
            String json = JSONArray.toJSONString(attachments);
            execProjectExamine.setAchment(json);
        }
        //新增主表数据:处理关联表字段
        execProjectExamine.setState(0);//数据状态 （0：存在  1：删除）
        execProjectExamine.setQuality(2);//是否质保 （0：是，1：否） 初始状态设置为2、用来查询
        execProjectExamine.setApprovalStatus(0);//业务主表审核状态 0-审核中  1-通过  2-驳回
        execProjectExamineMapper.insert(execProjectExamine);
        if(attachments != null && attachments.size() > 0){
            directoryService.saveProAttachment(attachments,DirectoryTypeEnum.PRO_RD_ACCEPTANCE.getCode(),String.valueOf(execProjectExamine.getId()),null,execProjectExamine.getProjectNumber());
        }
        //1、合同审批 2、协同审批 3、投标审批  4、立项审批  5、验收审批   6、成本变更审批  7、进度变更审批  8、研发立项审批  9、采购审批
        //增加审批人
        List<ApplyForApproval> checkList = execProjectExamine.getCheckList();
        if(checkList!=null){
            checkList.forEach(e ->{
                //业务表主键
                e.setRelationId(execProjectExamine.getId());
                //业务表编码
                e.setRelationCode(execProjectExamine.getProjectNumber());
                /**
                 * 关联审批分类 1、合同审批 2、协同审批 3、投标审批  4、立项审批  5、验收审批
                 * 6、成本变更审批  7、进度变更审批  8、研发立项审批  9、采购审批
                 */
                e.setRelationType(5);
            });
            applyForApprovalService.addApproval(checkList);
        }
        //增加抄送人
        List<ApplyForApproval> noticeList = execProjectExamine.getNoticeList();
        if(execProjectExamine.getNoticeList()!=null){
            noticeList.forEach(e -> {
                //业务表主键
                e.setRelationId(execProjectExamine.getId());
                //业务表编码
                e.setRelationCode(execProjectExamine.getProjectNumber());
                /**
                 * 关联审批分类 1、合同审批 2、协同审批 3、投标审批  4、立项审批  5、验收审批
                 * 6、成本变更审批  7、进度变更审批  8、研发立项审批  9、采购审批
                 */
                e.setRelationType(5);
            });
            applyForApprovalService.addCarbonCopy(noticeList);
        }
        return   0;
    }

    /**
     * 编辑项目验收信息
     * @param execProjectExamine
     * @return
     */
    @Override
    @Transactional
    public int update(ExecProjectExamine execProjectExamine) {
    	 List<AttachmentDto> attachments = execProjectExamine.getAttachments();
         if(attachments != null && attachments.size() > 0){
             String json = JSONArray.toJSONString(attachments);
             execProjectExamine.setAchment(json);
             directoryService.saveProAttachment(attachments,DirectoryTypeEnum.PRO_PM_ACCEPTANCE.getCode(),String.valueOf(execProjectExamine.getId()),null,execProjectExamine.getProjectNumber());
         }
        //1.验收相当于插入一条新的记录，和待验收项目是父子关系（同项目立项）
        execProjectExamine.setState(0);//数据状态 （0：存在  1：删除）
        List<ExecProjectContract> execProjectContracts = execProjectExamine.getExecProjectContracts();
        //合同字段处理
        if(execProjectContracts!=null&&execProjectContracts.size()>0){
            List<Long> resultList = execProjectContracts.stream().map(ExecProjectContract::getId).collect(Collectors.toList());
            String ids = org.apache.commons.lang3.StringUtils.join(resultList.toArray(),",");
            execProjectExamine.setCheckContract(ids);
        }
        Long userId = SecurityUtils.getCurrentUser().getId();
        execProjectExamine.setCreator(userId);
        execProjectExamine.setCreateTime(LocalDateTime.now());
        execProjectExamineMapper.insert(execProjectExamine);
        //2.新增遗留问题
        List<ExecProjectProblem> execProjectProblems = execProjectExamine.getExecProjectProblems();
        if (execProjectProblems !=null&&execProjectProblems.size()>0) {
            execProjectProblems.forEach(e->{
                e.setState(0);
                e.setProblemState("0");//初始问题为未解决
                e.setExamineId(execProjectExamine.getId());//对应验收阶段主键id
                e.setProjectNumber(execProjectExamine.getProjectNumber());
                execProjectProblemMapper.insert(e);
            });
        }
        //3.更新合同数据(更新回款计划、回款金额字段)
        if(execProjectContracts!=null&&execProjectContracts.size()>0){
            execProjectContracts.forEach(e->{
                UpdateWrapper<ExecProjectContract> updateWrapper = new UpdateWrapper();
                updateWrapper.lambda().eq(ExecProjectContract::getId,e.getId())
                        .set(ExecProjectContract::getReturnedMoney,e.getReturnedMoney())
                        .set(ExecProjectContract::getReturnedPlan,e.getReturnedPlan())
                        .set(ExecProjectContract::getUpdateTime, LocalDateTime.now());
                int update = execProjectContractMapper.update(null, updateWrapper);
                if(update>0){
                    ExecProject execProject = execProjectService.selectProject(execProjectExamine.getProjectNumber());
                    execProject.setCreated(2);
                    execProjectMapper.updateById(execProject);
                }
            });
        }
        //4.调用质保新增
        if(execProjectExamine.getQuality()==1) {
            projectWarrantyService.add(execProjectExamine);
        }
        return 0;
    }

    /**
     * 删除项目验收信息
     *
     * @param id
     * @return
     */
    @Override
    public int del(Long id) {
        ExecProjectExamine execProjectExamine = execProjectExamineMapper.selectById(id);
        if (execProjectExamine.getState() == 0){
            execProjectExamine.setState(1);
            return execProjectExamineMapper.updateById(execProjectExamine);
        }
        return 0;
    }

    /**
     * 查询项目验收信息
     *
     * @param execProjectExaminePage
     */
    @Override
    public Page<ExecProjectExamine> list(ExecProjectExaminePage execProjectExaminePage) {
        Page<ExecProjectExamine> pages = new Page<>(execProjectExaminePage.getPage(),execProjectExaminePage.getSize());
        QueryWrapper<ExecProjectExamine> queryWrapper = new QueryWrapper<>();
        Page<ExecProjectExamine> pageList = null;
        String type = execProjectExaminePage.getType();
        queryWrapper.lambda().eq(ExecProjectExamine::getState,0)
                .eq(ManagerEnum.GENERAL.toString().equals(SecurityUtils.getCurrentUser().getManager()), ExecProjectExamine::getCreator,SecurityUtils.getCurrentUser().getId())
        .like(StringUtils.isNotEmpty(execProjectExaminePage.getProjectName()),ExecProjectExamine::getProjectName,execProjectExaminePage.getProjectName())
        .eq(ExecProjectExamine::getQuality,type.equals("1")?2:type.equals("2")?1:0);
        pageList= execProjectExamineMapper.selectPage(pages,queryWrapper);
        List<ExecProjectExamine> records = pageList.getRecords();
        records.forEach(e -> {
            if (!type.equals("1")) {
                QueryWrapper<ExecProjectProblem> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(ExecProjectProblem::getProjectNumber, e.getProjectNumber())
                        .eq(ExecProjectProblem::getProblemState, "0");
                int count = execProjectProblemMapper.selectCount(wrapper);
                e.setLeftoverProblem(count > 0 ? "是" : "否");
            }
            if (e.getAchment() != null) {
                e.setAttachments(JSONObject.parseArray(e.getAchment(), AttachmentDto.class));
            }
        });
        return pageList;
    }

    /**
     * 根据id查看项目详情
     * @param id
     * @return
     */
    @Override
    public ExecProjectExamine selectById(Long id) {
        //查询主项目
        ExecProjectExamine execProjectExamine = execProjectExamineMapper.selectById(id);
        //返回合同金额
        execProjectExamine.setReturnedMoney(new BigDecimal(0.00));
        String  achment  =execProjectExamine.getAchment();
        if(StringUtils.isNotEmpty(achment)){       
        	execProjectExamine.setAttachment(JSONObject.parseArray(achment, Attachment.class));
        }
        //阶段验收
        if(StringUtils.isNotEmpty(execProjectExamine.getParentId())){
            //查询遗留问题
            QueryWrapper<ExecProjectProblem> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ExecProjectProblem::getExamineId,id);
            List<ExecProjectProblem> execProjectProblems = execProjectProblemMapper.selectList(queryWrapper);
            execProjectExamine.setExecProjectProblems(execProjectProblems);
            //查询已验收合同
            String checkContract = execProjectExamine.getCheckContract();
            if(StringUtils.isNotEmpty(checkContract)){
                String[] ids = checkContract.split(",");
                List<ExecProjectContract> execProjectContracts = execProjectContractMapper.selectContractsList(ids);
                execProjectExamine.setExecProjectContracts(execProjectContracts);
            }

        }else{
            //审批人列表
            //关联审批分类 1、合同审批 2、协同审批 3、投标审批  4、立项审批  5、验收审批
            //6、成本变更审批  7、进度变更审批  8、研发立项审批  9、采购审批
            List<ApplyForApproval> applyForApprovals = applyForApprovalService.selectApprovalUser(id,5);
            execProjectExamine.setCheckList(applyForApprovals);
            //抄送人列表
            //关联审批分类 1、合同审批 2、协同审批 3、投标审批  4、立项审批  5、验收审批
            //6、成本变更审批  7、进度变更审批  8、研发立项审批  9、采购审批
            List<ApplyForApproval> applyForApprovals1 = applyForApprovalService.selectCopyUser(id,5);
            execProjectExamine.setNoticeList(applyForApprovals1);
        }
        //查询全部合同
        List<ExecProjectContract> execProjectContracts = execProjectService.selectContract(execProjectExamine.getProjectNumber());
        if(execProjectContracts!=null) {       	
        	for (ExecProjectContract execProjectContract : execProjectContracts) {
        		if(execProjectContract.getReturnedMoney()==null) {
        			execProjectContract.setOutstandingAmount(execProjectContract.getMoney());
        		}else {
        		execProjectContract.setOutstandingAmount(execProjectContract.getMoney().subtract(execProjectContract.getReturnedMoney()));
        	}
        }
    }
        if(execProjectExamine.getQuality()==2) {
        	execProjectExamine.setQuality(0);
        }
        execProjectExamine.setExecProjectContract(execProjectContracts);
		return execProjectExamine;

}
}